const Axios = require('axios')
const apiMap = require('../config/api')
const statusCode = require('../config/statusCode')

const axios = Axios.create();
const defaultConf = {
  header: { "content-type": "application/json;charset=utf-8" }
}
function resolveError(resolve, e) {
  if (typeof e == 'string') {
    e = new Error(e)
  }
  console.error(e)
  resolve(statusCode.ERROE)
}
// 单请求
let ajax = function (opt) {
  return new Promise(resolve => {
    let arr = opt.url.split(':')
    let serverName = arr[0]
    let pathName = arr[1]
    if (!serverName || !pathName) {
      return resolveError(resolve, '请求地址错误，请检查！')
    }
    let module = apiMap[serverName]
    if (!module) {
      return resolveError(resolve, '请求地址错误，请检查！')
    }
    let { host, path, prefix } = module
    let url = host + '/' + (prefix || serverName) + path[pathName]
    if (!path[pathName]) {
      return resolveError(resolve, '请求地址错误，请检查！')
    }
    let { method, data, header } = opt
    let headers = Object.assign(defaultConf.header, header)
    method = (method || 'get').toUpperCase()
    axios({ url, headers, data, method }).then(res => {
      resolve(res.data)
    }, e => {
      resolveError(resolve, e)
    })
  })
}

// 并发请求
ajax.all = function (opts) {
  return new Promise(resolve => {
    let data = {}, count = 0
    let keys = Object.keys(opts)
    keys.forEach(key => {
      this(opts[key]).then(res => {
        data[key] = res
        if (++count == keys.length) {
          resolve({ ...statusCode.SUCCESS, data })
        }
      })
    })
  })
}

module.exports = ajax